<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="这里我做的这份笔记的意义仅仅是记录下自己初涉Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。  1 Spring IoC容器和Bean简介1.9 基于注解的容器配置 注解在配置Spring上比XML更好吗？ 两种方式并无绝对的更好。不过目前的趋势是使用注解，尤其是对于不是特别大的项目。  1.9.1 @Autowire@Autowire 用于自">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器)">
<meta property="og:url" content="http://example.com/2021/07/10/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B03%20%E2%80%94%E2%80%94%20IOC%E5%AE%B9%E5%99%A8%203%20(%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AEIOC%E5%AE%B9%E5%99%A8)/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="这里我做的这份笔记的意义仅仅是记录下自己初涉Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。  1 Spring IoC容器和Bean简介1.9 基于注解的容器配置 注解在配置Spring上比XML更好吗？ 两种方式并无绝对的更好。不过目前的趋势是使用注解，尤其是对于不是特别大的项目。  1.9.1 @Autowire@Autowire 用于自">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210526013456644.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0ODQ2MzI0,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2021-07-09T16:00:00.000Z">
<meta property="article:modified_time" content="2021-10-14T16:41:18.682Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="Spring核心">
<meta property="article:tag" content="JavaEE">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20210526013456644.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0ODQ2MzI0,size_16,color_FFFFFF,t_70">


<link rel="canonical" href="http://example.com/2021/07/10/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B03%20%E2%80%94%E2%80%94%20IOC%E5%AE%B9%E5%99%A8%203%20(%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AEIOC%E5%AE%B9%E5%99%A8)/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/07/10/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B03%20%E2%80%94%E2%80%94%20IOC%E5%AE%B9%E5%99%A8%203%20(%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AEIOC%E5%AE%B9%E5%99%A8)/","path":"2021/07/10/Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器)/","title":"Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器)"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器) | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-Spring-IoC%E5%AE%B9%E5%99%A8%E5%92%8CBean%E7%AE%80%E4%BB%8B"><span class="nav-number">1.</span> <span class="nav-text">1 Spring IoC容器和Bean简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-9-%E5%9F%BA%E4%BA%8E%E6%B3%A8%E8%A7%A3%E7%9A%84%E5%AE%B9%E5%99%A8%E9%85%8D%E7%BD%AE"><span class="nav-number">1.1.</span> <span class="nav-text">1.9 基于注解的容器配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-1-Autowire"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.9.1 @Autowire</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-2-Primary"><span class="nav-number">1.1.2.</span> <span class="nav-text">1.9.2 @Primary</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-3-Qualifier"><span class="nav-number">1.1.3.</span> <span class="nav-text">1.9.3 @Qualifier</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-4-Resource"><span class="nav-number">1.1.4.</span> <span class="nav-text">1.9.4 @Resource</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-5-%E5%B0%86%E6%B3%9B%E5%9E%8B%E7%94%A8%E4%BD%9C%E8%87%AA%E5%8A%A8%E8%A3%85%E9%85%8D%E9%99%90%E5%AE%9A%E7%AC%A6"><span class="nav-number">1.1.5.</span> <span class="nav-text">1.9.5 将泛型用作自动装配限定符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-9-4-Value"><span class="nav-number">1.1.6.</span> <span class="nav-text">1.9.4 @Value</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-10-%E7%B1%BB%E8%B7%AF%E5%BE%84%E6%89%AB%E6%8F%8F%E4%B8%8E%E6%89%98%E7%AE%A1%E7%BB%84%E4%BB%B6"><span class="nav-number">1.2.</span> <span class="nav-text">1.10 类路径扫描与托管组件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-10-1-ComponentScan"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.10.1 @ComponentScan</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-10-2-Bean"><span class="nav-number">1.2.2.</span> <span class="nav-text">1.10.2 @Bean</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-10-3-%E5%91%BD%E5%90%8D%E8%87%AA%E5%8A%A8%E6%A3%80%E6%B5%8B%E7%9A%84%E7%BB%84%E4%BB%B6"><span class="nav-number">1.2.3.</span> <span class="nav-text">1.10.3 命名自动检测的组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-10-4-Scope"><span class="nav-number">1.2.4.</span> <span class="nav-text">1.10.4 @Scope</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/07/10/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B03%20%E2%80%94%E2%80%94%20IOC%E5%AE%B9%E5%99%A8%203%20(%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AEIOC%E5%AE%B9%E5%99%A8)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器) | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器)
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-07-10 00:00:00" itemprop="dateCreated datePublished" datetime="2021-07-10T00:00:00+08:00">2021-07-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-10-15 00:41:18" itemprop="dateModified" datetime="2021-10-15T00:41:18+08:00">2021-10-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <blockquote>
<p>这里我做的这份笔记的意义仅仅是记录下自己初涉Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。</p>
</blockquote>
<h1 id="1-Spring-IoC容器和Bean简介"><a href="#1-Spring-IoC容器和Bean简介" class="headerlink" title="1 Spring IoC容器和Bean简介"></a>1 Spring IoC容器和Bean简介</h1><h2 id="1-9-基于注解的容器配置"><a href="#1-9-基于注解的容器配置" class="headerlink" title="1.9 基于注解的容器配置"></a>1.9 基于注解的容器配置</h2><blockquote>
<p><strong>注解</strong>在配置Spring上比<strong>XML</strong>更好吗？ 两种方式并无绝对的更好。不过目前的趋势是使用注解，尤其是对于不是特别大的项目。</p>
</blockquote>
<h3 id="1-9-1-Autowire"><a href="#1-9-1-Autowire" class="headerlink" title="1.9.1 @Autowire"></a>1.9.1 @Autowire</h3><p><strong>@Autowire</strong> 用于自动装配，按照 <strong>类型</strong> 装配。</p>
<ol>
<li>注解字段</li>
<li>注解构造器</li>
<li>注解方法</li>
</ol>
<p>其中，不建议使用 @Autowire 注入，这强依赖于 Spring 上下文的，无法在脱离ioc容器创建对象，比如在进行单元测试的时候。<br>使用构造器注入，表达强依赖关系。<br>使用方法（不一定是setter），表达依赖的可选择关系。</p>
<h3 id="1-9-2-Primary"><a href="#1-9-2-Primary" class="headerlink" title="1.9.2 @Primary"></a>1.9.2 @Primary</h3><p>由于@Autowire是按类型自动装配的，如果有过个bean的话Spring不知道找那个，<br>可以使用 <strong>@Primary</strong> 指定 bean 的优先级。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Primary</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> class ...&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以及</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MovieConfiguration</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="meta">@Primary</span></span><br><span class="line">    <span class="keyword">public</span> MovieCatalog <span class="title function_">firstMovieCatalog</span><span class="params">()</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> MovieCatalog <span class="title function_">secondMovieCatalog</span><span class="params">()</span> &#123; ... &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-9-3-Qualifier"><a href="#1-9-3-Qualifier" class="headerlink" title="1.9.3 @Qualifier"></a>1.9.3 @Qualifier</h3><p>配合 @Autowire 使用，可以根据 bean 的名字进行精确匹配。<br>此注解可以使用在 方法、字段、类型、参数，相当于在需要根据name进行标识的时候，就使用它。</p>
<p>注：<br>可能有人想用 <strong>@Resource</strong> 去彻底代替 @Autowire + @Qualifier。<br>在一定场景下是可以的。<br>但是 <strong>@Resource 只能用于字段，和单个参数的setter</strong>，对于注解构造函数和多个参数的方法，它无能为力。不过， @Autowire + @Qualifier 没有这个限制。</p>
<p>官方文档这里还讲了 自定义的 @Qualifier ，这里就不细讲了。</p>
<h3 id="1-9-4-Resource"><a href="#1-9-4-Resource" class="headerlink" title="1.9.4 @Resource"></a>1.9.4 @Resource</h3><p> <code>@Resource</code>有两个属性<code>name</code>、<code>type</code><br>匹配规则：</p>
<ul>
<li>后面没有任何内容，<strong>默认通过name属性</strong>去匹配bean，找不到再按type去匹配；</li>
<li>指定了name或者type则根据指定的类型去匹配bean；</li>
<li>指定了name和type则根据指定的name和type去匹配bean，任何一个不匹配都将报错。</li>
</ul>
<h3 id="1-9-5-将泛型用作自动装配限定符"><a href="#1-9-5-将泛型用作自动装配限定符" class="headerlink" title="1.9.5 将泛型用作自动装配限定符"></a>1.9.5 将泛型用作自动装配限定符</h3><p>暂略。</p>
<h3 id="1-9-4-Value"><a href="#1-9-4-Value" class="headerlink" title="1.9.4 @Value"></a>1.9.4 @Value</h3><p>@Value 通常用于注入外部属性。<br>这里还用到了 Spring表达式，不过这里仅仅使用读取即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MovieRecommender</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String catalog;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">MovieRecommender</span><span class="params">(<span class="meta">@Value(&quot;$&#123;catalog.name&#125;&quot;)</span> String catalog)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.catalog = catalog;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 application.properties</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">catalog.name=MovieCatalog</span><br></pre></td></tr></table></figure>


<p>还可以使用SpEL进行读取值后动态计算生成值。</p>
<h2 id="1-10-类路径扫描与托管组件"><a href="#1-10-类路径扫描与托管组件" class="headerlink" title="1.10 类路径扫描与托管组件"></a>1.10 类路径扫描与托管组件</h2><h3 id="1-10-1-ComponentScan"><a href="#1-10-1-ComponentScan" class="headerlink" title="1.10.1 @ComponentScan"></a>1.10.1 @ComponentScan</h3><p>要<strong>自动检测这些类并注册相应的bean</strong>，就可以使用 <strong>@ComponentScan</strong>。</p>
<p>它的作用，找到这些bean,并把它注册到 ioc 容器里， 就像我们手动在 xml 配置一样。</p>
<p>对于SpringBoot应用这个注解可能不会直接被我们使用，<br>原因是 @SpringBootApplication已经使用了 这个注解，而这个注解会扫描 com.xxx.xxx包及其子包下所有的@Component 及其派生注解，所以一般情况下我们用不着。</p>
<p>但是如果有类写在启动类所在包的外面，而你又想使用它，就得用上这个注解了。</p>
<p>使用方法：<br>指定扫描的包（子包会自动扫描），指定过滤器。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ComponentScan(basePackages = &quot;org.example&quot;,</span></span><br><span class="line"><span class="meta">        includeFilters = @Filter(type = FilterType.REGEX, pattern = &quot;.*Stub.*Repository&quot;),</span></span><br><span class="line"><span class="meta">        excludeFilters = @Filter(Repository.class))</span></span><br></pre></td></tr></table></figure>

<h3 id="1-10-2-Bean"><a href="#1-10-2-Bean" class="headerlink" title="1.10.2 @Bean"></a>1.10.2 @Bean</h3><p>@Bean注释的作用与<bean/>元素相同。</p>
<p>@Bean可以结合其他注解使用<br>这些注解基本上是补全了XML的功能</p>
<ul>
<li>如<br>@Primary :优先级，当有两个相同类型的Spring Bean，如果有一个被声明了是@Primary，那么@Autowired会注入这个带有@Primary的。<br>@Scope :作用域，默认有singleton&#x2F;prototype，单例和每次注入重新初始化，<br>@Profile :见@Configuration<br>@Lazy :见@Configuration</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//@Component</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BeanHolder</span> &#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> ExampleBean <span class="title function_">exampleBean</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">ExampleBean</span>();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 在类内调用，同样也会经过代理</span></span><br><span class="line">    <span class="comment">// （ 很好理解，cglib生成的子类override上面的getExampleBean方法后，调用f()时，</span></span><br><span class="line">    <span class="comment">// 根据类的多态，此时调用的getExampleBean方法是被增强过的方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">f</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(exampleBean());</span><br><span class="line">        System.out.println(exampleBean());</span><br><span class="line">        System.out.println(exampleBean());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>它和如下的xml配置等效</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;exampleBean&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.xxx.BeanHolder&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>如果把这里的 <strong>@Configuration</strong>换成 <strong>@Component</strong>会怎样？<br>注意，@Configuration类下被 @Bean 注解的方法，调用的时候会得到CGLIB代理的增强，<br>而@Component下的@Bean方法不经过代理，是标准的java调用。</p>
</li>
<li><p>如果@Bean修饰的方法被 static呢？<br>注意CGLIB生成的子类只会override非静态方法，所以static的@Bean方法不会被容器拦截。<br>技术上来说，CGLIB会动态生成BeanHolder的子类，然后override那个@Bean代理的方法。</p>
</li>
</ul>
<p>注意，看到下面的图，你通过Spring容器拿到的类，其实已经不是你自己写的类了，而是经过cglib加强过的类。<br><img src="https://img-blog.csdnimg.cn/20210526013456644.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0ODQ2MzI0,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h3 id="1-10-3-命名自动检测的组件"><a href="#1-10-3-命名自动检测的组件" class="headerlink" title="1.10.3 命名自动检测的组件"></a>1.10.3 命名自动检测的组件</h3><p>Spring自己生成的bean的名字是有规则的，就是类名答第一个字母变成小写，而你可以自定义名称生成规则（不过似乎很鸡肋，没什么用）。</p>
<h3 id="1-10-4-Scope"><a href="#1-10-4-Scope" class="headerlink" title="1.10.4 @Scope"></a>1.10.4 @Scope</h3><p>这个注解可以用在Bean class 和@Bean 方法上，用来指定作用域。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Scope(&quot;prototype&quot;)</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> class ...&#123;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="meta">@Scope(&quot;prototype&quot;)</span></span><br><span class="line"><span class="keyword">public</span> MyBean <span class="title function_">myBean</span><span class="params">()</span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<blockquote>
<p>参考资料</p>
<p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/current-SNAPSHOT/reference/html/core.html#spring-core">Spring官方文档</a></p>
<p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/">doc index</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Spring%E6%A0%B8%E5%BF%83/" rel="tag"># Spring核心</a>
              <a href="/tags/JavaEE/" rel="tag"># JavaEE</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/07/05/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B02%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%202%20%EF%BC%88Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3%EF%BC%89/" rel="prev" title="Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）">
                  <i class="fa fa-chevron-left"></i> Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/07/21/%E8%BF%99%E6%AC%A1%E5%BD%BB%E5%BA%95%E8%A7%A3%E5%86%B3%E5%9C%A8Hexo%E4%B8%AD%E6%B8%B2%E6%9F%93MathJax%E6%95%B0%E5%AD%A6%E5%85%AC%E5%BC%8F%E5%87%BA%E7%8E%B0%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%81%EF%BC%81%EF%BC%81/" rel="next" title="这次彻底解决在Hexo中渲染MathJax数学公式出现的问题！！！">
                  这次彻底解决在Hexo中渲染MathJax数学公式出现的问题！！！ <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
